#include "face_beauty_canvas.h"

#include <QtGui/QPainter>
#include <QtCore/QPoint>
#include <QtCore/QRect>

FaceBeautyViewFinder::FaceBeautyViewFinder(ImageHandler *filter)
{
    handler_ = filter;
}

FaceBeautyViewFinder::~FaceBeautyViewFinder()
{

}

QList<QVideoFrame::PixelFormat> FaceBeautyViewFinder::supportedPixelFormats(QAbstractVideoBuffer::HandleType type) const
{
    QList<QVideoFrame::PixelFormat> pix_list;

    pix_list.push_back(QVideoFrame::Format_RGB32);
    return pix_list;
}

bool FaceBeautyViewFinder::present(const QVideoFrame &frame)
{
    handler_->ProccessFrame(new QImage((frame.image().mirrored())));
    return true;
}

FaceBeautyCanvas::FaceBeautyCanvas(QWidget *parent, Qt::WindowFlags f): QWidget(parent, f), images_(200)
{

    QPainter painter(this);
    painter.fillRect(this->rect(), Qt::black);
}

FaceBeautyCanvas::~FaceBeautyCanvas()
{

}

int FaceBeautyCanvas::ProccessFrame(QImage *img)
{
    images_.Push(img);
    update();

    return 0;
}

void FaceBeautyCanvas::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);


    if(images_.Empty()) {
        return;
    }

    // clear
    painter.fillRect(this->rect(), Qt::black);

    QImage *img;
    if(!images_.Pop(img)) {
        return;
    }

    QRectF source(img->rect());
    QRectF target(this->rect());

    if(source == target) {
        painter.drawImage(QPoint(0,0), *img);
        return;
    }

    // rescale and move to the device center
    QImage img_rescaled;
    qreal xshift, yshift;

    if((source.width()/source.height()) >= (target.width()/target.height())) {
        img_rescaled = img->scaledToWidth(target.width());
        yshift = (target.height() - img_rescaled.height())/2;
        painter.drawImage(QPointF(0, yshift), img_rescaled);

    } else {
        img_rescaled = img->scaledToHeight(target.height());
        xshift = (target.width() - img_rescaled.width())/2;
        painter.drawImage(QPointF(xshift, 0), img_rescaled);
    }
}
